/*
The MIT License

Copyright (c) 2010 Yuen Ho Wong

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

var app = safari.application;
var ext = safari.extension;
var settings = ext.settings
var secureSettings = ext.secureSettings;

// START Helper functions
function broadcastMessage(name, data) {
    for (var i = 0; i < app.browserWindows.length; i++) {
        var win = app.browserWindows[i];
        for (var j = 0; j < win.tabs.length; j++) {
            var tab = win.tabs[j];
            tab.page.dispatchMessage(name, data);
        }
    }    
}

function getCurrentURL () {
    return safari.application.activeBrowserWindow.activeTab.url;
}

function sendMessageToCurrentPage (name, data) {
    safari.application.activeBrowserWindow.activeTab.page.dispatchMessage(name, data);
}

// START event handlers
function contextMenuItemValidateListener (event) {
    if (event.command === "addBookmark") {
        if (!getCurrentURL()) {
            event.target.disabled = true;
        }
    }
}

function contextMenuItemCommandListener (event) {
    if (event.command === "addBookmark") {
        sendMessageToCurrentPage("addBookmark", null);
    }
}

function toolbarItemCommandListener (event) {
    if (event.command === "toolbarItem") {
        sendMessageToCurrentPage('addBookmark', null);
    }
}

// TODO: send an error notice back to the page
function errorListener (event) {
    return function (resp) {
        event.target.page.dispatchMessage('error', "XHR Headers: " + resp.getAllHeaders() + '\n' + 'XHR Response Body: ' + resp.responseText + '\n');
    }
}

function respondToSuggestMessage (event) {
    var url = event.message;
    var accessToken = secureSettings.getItem('accessToken');
    var oauth = new OAuth();
    if (accessToken) {
        accessToken = accessToken.evalJSON();
        if (!oauth.hasExpired(accessToken)) {
            var delicious = new Delicious(oauth);
            delicious.suggest(
                url,
                accessToken,
                function (resp) {
                    var suggestions = {};
                    var xml = resp.responseXML;

                    var popularNodes = xml.getElementsByTagName('popular');
                    var recommendedNodes = xml.getElementsByTagName('recommended');

                    if (popularNodes) {
                        suggestions.popular = [];
                        for (var i = 0; i < popularNodes.length; i++) {
                            suggestions.popular.push(popularNodes.item(i).textContent);
                        }
                    }

                    if (recommendedNodes) {
                        suggestions.recommended = [];
                        for (var i = 0; i < recommendedNodes.length; i++) {
                            suggestions.recommended.push(recommendedNodes.item(i).textContent);
                        }
                    }

                    event.target.page.dispatchMessage('suggestions', suggestions);
                },
                errorListener(event));
        }
    }
}

function respondToAddBookmarkMessage (event) {
    var params = event.message;
    var accessToken = secureSettings.getItem('accessToken');
    var oauth = new OAuth();
    if (accessToken) {
        accessToken = accessToken.evalJSON();
        if (!oauth.hasExpired(accessToken)) {
            var delicious = new Delicious(oauth);
            delicious.bookmark(params,
                               accessToken,
                               null, // TODO: send a success message back to the page
                               errorListener(event));
        }
    }
}

function respondToLoginMessage (event) {
    var targetWindow = event.target.browserWindow;
    var accessToken = secureSettings.getItem('accessToken');
    if (accessToken) {
        accessToken = accessToken.evalJSON();
        var oauth = new OAuth();
        if (oauth.hasExpired(accessToken)) {
            oauth.renewAccessToken(accessToken, function (response) {
                accessToken = response.responseText.toQueryParams();
                accessToken.lastModifiedTime = Math.round(new Date().getTime() / 1000);
                secureSettings.setItem('accessToken', Object.toJSON(accessToken));
            }, errorListener(event));
        }
        event.target.page.dispatchMessage('loggedIn');
    }
    else {
        var oauth = new OAuth();
        var requestToken = oauth.getRequestToken(function (response) {
            var token = response.responseText.toQueryParams();
            secureSettings.setItem('requestToken', Object.toJSON(token));
            popupOAuth(token);
        }, errorListener(event));
        event.target.page.dispatchMessage('notLoggedIn');
    }
}

function respondToRequestAccessTokenMessage (event) {
    var oauth = new OAuth();
    var requestToken = secureSettings.getItem('requestToken');
    if (requestToken) {
        requestToken = requestToken.evalJSON();
        oauth.getAccessToken(requestToken, event.message, function (response) {
            var accessToken = response.responseText.toQueryParams();
            accessToken.lastModifiedTime = Math.round(new Date().getTime() / 1000);
            secureSettings.setItem('accessToken', Object.toJSON(accessToken));
            event.target.page.dispatchMessage('loggedIn');
        }, errorListener(event));
    }
}

function pageProxyMessageListener (event) {

    switch (event.name) {
    case 'suggest':
        respondToSuggestMessage(event);
        break;
    case 'addBookmark':
        respondToAddBookmarkMessage(event);
        break;
    case 'login':
        respondToLoginMessage(event);
        break;
    case 'requestAccessToken':
        respondToRequestAccessTokenMessage(event);
        break;
    case 'getAddBookmarkShortcut':
        var currentShortcut = settings.getItem('addBookmark');
        var targetPage = event.target.page;
        if (targetPage) { // target page could be empty if an empty tab is opened
            targetPage.dispatchMessage('setupAddBookmarkShortcut', currentShortcut);
        }
        break;
    }
}

function popupOAuth (requestToken) {
    var oauth = new OAuth();
    var requestAuthUrl = oauth.getRequestAuthUrl(requestToken);
    var newWindow = safari.application.openBrowserWindow();
    ext.addContentScriptFromURL(ext.baseURI + 'yahoo-oauth.js', ['https://*login.yahoo.com/*'], null, false);
    newWindow.activeTab.url = requestAuthUrl;
}

app.addEventListener('requestTokenReceived', popupOAuth, false);
app.addEventListener("command", toolbarItemCommandListener, false);
app.addEventListener("command", contextMenuItemCommandListener, false);
app.addEventListener("validate", contextMenuItemValidateListener, false);
app.addEventListener('message', pageProxyMessageListener, false);

function isKeyboardShortcutValid(shortcut) {
    var tokens = shortcut.split('+');
    if (tokens.length < 2) {
        return false;
    }

    var key = tokens.pop();

    if (key === '' || key === null || key === undefined) {
        return false;
    }

    var modifiers = tokens;

    if (!modifiers.every(function (v, i, a) {
        v = v.toLowerCase();
        return v === 'ctrl' || v === 'shift' || v === 'alt' || v === 'meta';
    })) {
        return false;
    }

    return true;
}

function settingsChangedListener(event) {
    switch (event.key) {
    case 'addBookmark':
        var shortcut = event.newValue;
        if (!isKeyboardShortcutValid(shortcut)) {
            alert('Invalid keyboard shortcut.\nKeyboard shortcut must be in the form of Modifier[+Modifier..]+Key, where Modifier is one of Ctrl, Alt, Shift or Meta.');
        }
        broadcastMessage('changeAddBookmarkShortcut', {'new': event.newValue, 'old': event.oldValue});
        break;
    }
}

settings.addEventListener('change', settingsChangedListener, false);
// END event handlers

var OAuth = function (kwargs) {

    this.APP_ID = 'woDuM678';
    this.CONSUMER_KEY = 'dj0yJmk9NTNhU0hoWnhGdnBCJmQ9WVdrOWQyOUVkVTAyTnpnbWNHbzlOVE0yTnpNeE1UWXkmcz1jb25zdW1lcnNlY3JldCZ4PWIw';
    this.CONSUMER_SECRET = 'cbc7a63e0a42ef899adc5c6cb16bd93177566566';

    if (kwargs) {
        for (k in kwargs) {
            this[k] = kwargs[k];
        }
    }

    if (!this.lang_pref) {
        this.lang_pref = navigator.language;
    }
};

OAuth.prototype.percentEncode = function (s) {
    return encodeURIComponent(s).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').  
        replace(/\)/g, '%29').replace(/\*/g, '%2A');
};

OAuth.prototype.percentEncodePlus = function (s) {
    return encodeURIComponent(s).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').  
        replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
};

OAuth.prototype.hasExpired = function (token) {
    var now = Math.round(new Date().getTime() / 1000);
    var lmt = token.lastModifiedTime;
    var timeElapsed = now - lmt;
    if (token.oauth_expires_in <= timeElapsed) {
        return true;
    }

    return false;
};

OAuth.prototype.getNonce = function () {
    return $R(0, 10, true).toArray().map(function (item) {
        return Math.round(Math.random() * 100) % 10;
    }).join('');
};

OAuth.prototype.getTimestamp = function () {
    return Math.round(new Date().getTime() / 1000);
}

OAuth.prototype.renewAccessToken = function (accessToken, succFunc, failFunc) {
    var self = this;

    var params = {
        oauth_nonce: self.getNonce(),
        oauth_timestamp: self.getTimestamp(),
        oauth_consumer_key: self.CONSUMER_KEY,
        oauth_signature_method: 'plaintext',
        oauth_version: '1.0',
        oauth_signature: self.CONSUMER_SECRET + '&' + accessToken.oauth_token_secret,
        oauth_token: accessToken.oauth_token,
        oauth_session_handle: accessToken.oauth_session_handle
    };

    new Ajax.Request('https://api.login.yahoo.com/oauth/v2/get_token', {
        parameters: params,
        onSuccess: succFunc,
        onFailure: failFunc
    });

};

OAuth.prototype.getAccessToken = function (requestToken, oauth_verifier, succFunc, failFunc) {
    var self = this;

    var params = {
        oauth_nonce: self.getNonce(),
        oauth_timestamp: self.getTimestamp(),
        oauth_consumer_key: self.CONSUMER_KEY,
        oauth_signature_method: 'plaintext',
        oauth_version: '1.0',
        oauth_signature: self.CONSUMER_SECRET + '&' + requestToken.oauth_token_secret,
        oauth_verifier: oauth_verifier,
        oauth_token: requestToken.oauth_token
    };

    new Ajax.Request('https://api.login.yahoo.com/oauth/v2/get_token', {
        parameters: params,
        onSuccess: succFunc,
        onFailure: failFunc
    });
};

OAuth.prototype.getRequestToken = function (succFunc, failFunc) {
    var self = this;

    var params = {
        oauth_nonce: self.getNonce(),
        oauth_timestamp: self.getTimestamp(),
        oauth_consumer_key: self.CONSUMER_KEY,
        oauth_signature_method: 'plaintext',
        oauth_version: '1.0',
        oauth_signature: self.CONSUMER_SECRET + '&',  // the ending & is required for plaintest signature method
        xoauth_lang_pref: self.lang_pref,
        oauth_callback: 'oob'
    };

    new Ajax.Request('https://api.login.yahoo.com/oauth/v2/get_request_token', {
        parameters: params,
        onSuccess: succFunc,
        onFailure: failFunc
    });
};

OAuth.prototype.getRequestAuthUrl = function (requestToken) {
    return requestToken.xoauth_request_auth_url;
};

OAuth.prototype.getBaseString = function (method, requestUrl, requestParams, oauthParams) {
    var self = this;

    oauthParams = self.filterParams(oauthParams);
    requestParams = self.filterParams(requestParams, self.percentEncodePlus);

    var pairs = oauthParams.toArray();
    pairs.concat(requestParams.toArray());
    pairs = pairs.collect(function (e) {
        return e.join('=');
    });
    pairs.sort();
    pairs = pairs.join('&');

    var baseString = method.trim().toUpperCase() + '&' + self.percentEncode(requestUrl) + '&' + self.percentEncode(pairs);
    return baseString;
};

OAuth.prototype.filterParams = function (params, encoder) {

    if (!encoder) {
        encoder = this.percentEncode;
    }

    var filteredParams = $H();
    params = $H(params);
    params.keys().each(function (key) {
        var val = params.get(key);
        if (val !== null && val !== undefined && val !== NaN) {
            if (typeof val === 'string' && val.trim().length > 0 || typeof val === 'number') {
                filteredParams.set(encoder(key), encoder(val));
            }
        }
    });
    return filteredParams;
}

OAuth.prototype.getSignature = function (accessToken, baseString) {
    var key = this.percentEncode(this.CONSUMER_SECRET) + '&' + this.percentEncode(accessToken.oauth_token_secret);
    var hmac = Crypto.HMAC(Crypto.SHA1, baseString, key, { asBytes: true });
    return Crypto.util.bytesToBase64(hmac);
};

OAuth.prototype.request = function (url, params, accessToken, succFunc, failFunc) {
    var self = this;

    var oauthParams = $H({
        oauth_nonce: self.getNonce(),
        oauth_timestamp: self.getTimestamp(),
        oauth_consumer_key: self.CONSUMER_KEY,
        oauth_signature_method: 'HMAC-SHA1',
        oauth_version: '1.0',
        oauth_token: accessToken.oauth_token
    });

    var baseString = this.getBaseString('POST', url, params, oauthParams);
    var signature = this.getSignature(accessToken, baseString);
    var authHeader = [];
    oauthParams.each(function (e) {
        authHeader.push(self.percentEncode(e.key) + '="' + self.percentEncode(e.value) + '"');
    });
    authHeader.unshift('realm="yahooapis.com"');
    authHeader.push('oauth_signature="' + self.percentEncode(signature) + '"');
    authHeader = 'OAuth ' + authHeader.join(',');

    new Ajax.Request(url, {
        requestHeaders: {
            Authorization: authHeader
        },
        method: "POST",
        parameters: params,
        onSuccess: succFunc,
        onFailure: failFunc
    });

};

var Delicious = function (oauth) {
    this.oauth = oauth;
};

Delicious.prototype.bookmark = function (params, accessToken, succFunc, failFunc) {
    return this.oauth.request('http://api.del.icio.us/v2/posts/add', params, accessToken, succFunc, failFunc);
};

Delicious.prototype.suggest = function (url, accessToken, succFunc, failFunc) {
    return this.oauth.request('http://api.del.icio.us/v2/posts/suggest', { url: url }, accessToken, succFunc, failFunc);
};